<template>
  <n-tree
    class="slash-tree"
    style="max-height: 600px; min-height: 600px; overflow-y: scroll"
    :block-line="false"
    :block-node="true"
    cascade
    draggable
    expand-on-dragenter
    default-expand-all
    selectable="true"
    :data="treeData"
    :node-props="nodeProps"
    key-field="id"
    :on-drop="onDrop"
    :render-label="renderLabel"
    :render-prefix="renderPrefix"
    :render-suffix="renderSuffix"
    label-field="deptName"
    :default-expanded-keys="defaultExpandedKeys"
  />
</template>

<script lang="ts">
  import { defineComponent, h, onMounted, ref } from 'vue';
  import { NPopover, NTooltip, TreeOption } from 'naive-ui';
  import httpApi from './httpApi';
  import { SlashAppContext } from 'slash-admin';
  import { doDeleteModal, doSaveModal, doUpdateModal } from './Service';
  import { AuthCodes } from '@/apis/auth-code';
  import { checkAuthShow } from 'slash-admin';
  export default defineComponent({
    components: {},
    emits: ['select'],
    setup(props, ctx) {
      const renderLabel = (info: {
        option: Record<string, any> & TreeOption;
        checked?: boolean;
        selected?: boolean;
      }) => {
        const { option } = info;
        return h(
          NTooltip,
          {},
          {
            default: option.deptName,
            trigger: h(
              'div',
              {
                class: 'ellipsis-text',
              },
              option.deptName
            ),
          }
        );
      };
      const renderPrefix = (info: {
        option: Record<string, any> & TreeOption;
        checked?: boolean;
        selected?: boolean;
      }) => {
        const { option } = info;
        return h('i', {
          class: `${
            option.children && option.children.length > 0 ? 'ri-folder-5-fill' : 'ri-folder-5-line'
          }`,
          style: {
            color: `#1e80ff`,
            marginRight: '0px',
          },
        });
      };
      const renderSuffix = (info: {
        option: Record<string, any> & TreeOption;
        checked?: boolean;
        selected?: boolean;
      }) => {
        const { option } = info;
        return h(
          NPopover,
          {
            trigger: 'hover',
            placement: 'bottom',
          },
          {
            trigger: () =>
              h(
                'i',
                {
                  class: 'ri-more-2-fill btn-icon',
                  style: {
                    cursor: 'pointer',
                    fontSize: '16px',
                  },
                },
                ''
              ),
            default: () =>
              h(
                'div',
                {
                  style: {
                    display: 'flex',
                    flexDirection: 'column',
                    alignItems: 'center',
                    justifyContent: 'center',
                    gap: '5px',
                  },
                },
                {
                  default: () => [
                    h(
                      'div',
                      {
                        onVnodeMounted: async (vNode) => {
                          await checkAuthShow(vNode.el as any, AuthCodes['用户管理目录新增']);
                        },
                        style: {
                          cursor: 'pointer',
                          fontSize: '16px',
                          display: 'flex',
                          alignItems: 'center',
                          gap: '5px',
                        },
                        onClick: (async (option: any) => {
                          await doSaveModal(option);
                          await reload();
                        }).bind(null, option),
                      },
                      h('i', {
                        class: 'ri-add-line btn-icon',
                      }),
                      '新建部门'
                    ),
                    h(
                      'div',
                      {
                        onVnodeMounted: async (vNode) => {
                          await checkAuthShow(vNode.el as any, AuthCodes['用户管理目录编辑']);
                        },
                        style: {
                          cursor: 'pointer',
                          fontSize: '16px',
                          display: 'flex',
                          alignItems: 'center',
                          gap: '5px',
                        },
                        onClick: (async (option: any) => {
                          await doUpdateModal(option);
                          await reload();
                        }).bind(null, option),
                      },
                      h('i', {
                        class: 'ri-edit-line btn-icon',
                      }),
                      '编辑部门'
                    ),
                    h(
                      'div',
                      {
                        onVnodeMounted: async (vNode) => {
                          await checkAuthShow(vNode.el as any, AuthCodes['用户管理目录删除']);
                        },
                        style: {
                          cursor: 'pointer',
                          fontSize: '16px',
                          display: 'flex',
                          alignItems: 'center',
                          gap: '5px',
                        },
                        onClick: (async (option: any) => {
                          await doDeleteModal(option);
                          await reload();
                        }).bind(null, option),
                      },
                      h('i', {
                        class: 'ri-delete-bin-7-line btn-icon',
                      }),
                      '删除部门'
                    ),
                  ],
                }
              ),
          }
        );
        // return h('span', [
        //   h('i', {
        //     onVnodeMounted: async (vNode) => {
        //       await checkAuthShow(vNode.el as any, AuthCodes['用户管理目录新增']);
        //     },
        //     class: 'ri-add-fill ',
        //     style: {
        //       marginRight: '5px',
        //       color: '#727070',
        //       fontSize: '20px',
        //     },
        //     onClick: (async (option: any) => {
        //       await doSaveModal(option);
        //       await reload();
        //     }).bind(null, option),
        //   }),
        //   h('i', {
        //     onVnodeMounted: async (vNode) => {
        //       await checkAuthShow(vNode.el as any, AuthCodes['用户管理目录编辑']);
        //     },
        //     class: 'ri-edit-line',
        //     style: {
        //       marginRight: '5px',
        //       fontSize: '16px',
        //       color: '#727070',
        //     },
        //     onClick: (async (option: any) => {
        //       await doUpdateModal(option);
        //       await reload();
        //     }).bind(null, option),
        //   }),
        //   h('i', {
        //     onVnodeMounted: async (vNode) => {
        //       await checkAuthShow(vNode.el as any, AuthCodes['用户管理目录删除']);
        //     },
        //     class: 'ri-delete-bin-7-line ',
        //     style: {
        //       marginRight: '5px',
        //       fontSize: '16px',
        //       color: '#727070',
        //     },
        //     onClick: (async (option: any) => {
        //       await doDeleteModal(option);
        //       await reload();
        //     }).bind(null, option),
        //   }),
        // ]);
      };
      const nodeProps = ({ option }: { option: TreeOption }) => {
        return {
          onClick() {
            ctx.emit('select', option);
          },
        };
      };
      const onDrop = async (data: {
        node: TreeOption;
        dragNode: TreeOption;
        dropPosition: 'before' | 'inside' | 'after';
        event: DragEvent;
      }) => {
        console.log('拖动', data);
        const { node, dragNode, dropPosition } = data;
        const updateData = {
          id: dragNode.id,
          position: dropPosition,
          targetId: node.id,
        };
        await httpApi.doUpdateOrderIndex(updateData);
        await reload();
      };
      onMounted(() => {
        init();
      });
      const reload = async () => {
        await init();
      };
      const treeData = ref<any>([]);
      const init = async () => {
        const appCode = SlashAppContext.getRequest().appCode || '';
        const msg = await httpApi.selectTreeList();
        treeData.value = [
          {
            id: 0,
            deptName: '全部组织架构',
            groupCode: '',
            children: [...msg.data],
          },
        ];
        console.log(treeData.value);
      };
      return {
        renderPrefix,
        renderSuffix,
        renderLabel,
        onDrop,
        treeData,
        nodeProps,
        defaultExpandedKeys: ref(['40', '41']),
      };
    },
  });
</script>

<style lang="less" scoped>
  .slash-tree {
    ::v-deep(.n-tree-node) {
      .n-tree-node-content__suffix {
        visibility: hidden;
      }

      &:hover {
        .n-tree-node-content__suffix {
          visibility: visible;
        }
      }
    }
  }
  :deep(.n-tree-node-content) {
    .n-tree-node-content__text {
      width: calc(100% - 100px);
    }
    .ellipsis-text {
      white-space: nowrap;
      overflow: hidden;
      text-overflow: ellipsis;
      margin: 0;
    }
  }
</style>
